import React from 'react';
import { Spin, Alert } from 'antd';
import { PageLoading, CardLoading } from './LoadingSpinner';
import { EmptyState, ErrorState, ListEmptyState } from './EmptyState';

/**
 * 通用数据渲染组件
 * 根据数据状态自动渲染加载、错误、空状态或实际内容
 */
const DataRenderer = ({
  loading = false,
  error = null,
  data = null,
  children,
  // 加载状态配置
  loadingComponent,
  loadingProps = {},
  // 错误状态配置
  errorComponent,
  errorProps = {},
  showErrorAlert = true,
  // 空状态配置
  emptyComponent,
  emptyProps = {},
  emptyType = 'data',
  // 数据检查配置
  isEmpty = (data) => {
    if (data === null || data === undefined) return true;
    if (Array.isArray(data)) return data.length === 0;
    if (typeof data === 'object') return Object.keys(data).length === 0;
    return false;
  },
  // 其他配置
  minHeight = '200px',
  style = {}
}) => {
  const containerStyle = {
    minHeight,
    ...style
  };

  // 加载状态
  if (loading) {
    if (loadingComponent) {
      return React.cloneElement(loadingComponent, loadingProps);
    }
    return (
      <div style={containerStyle}>
        <PageLoading {...loadingProps} />
      </div>
    );
  }

  // 错误状态
  if (error) {
    if (errorComponent) {
      return React.cloneElement(errorComponent, { error, ...errorProps });
    }
    
    if (showErrorAlert) {
      return (
        <div style={containerStyle}>
          <Alert
            message="加载失败"
            description={error.message || '数据加载时发生错误，请稍后重试'}
            type="error"
            showIcon
            style={{ margin: '20px 0' }}
          />
          <ErrorState error={error} {...errorProps} />
        </div>
      );
    }
    
    return (
      <div style={containerStyle}>
        <ErrorState error={error} {...errorProps} />
      </div>
    );
  }

  // 空状态
  if (isEmpty(data)) {
    if (emptyComponent) {
      return React.cloneElement(emptyComponent, emptyProps);
    }
    return (
      <div style={containerStyle}>
        <EmptyState type={emptyType} {...emptyProps} />
      </div>
    );
  }

  // 渲染实际内容
  return typeof children === 'function' ? children(data) : children;
};

/**
 * 表格数据渲染组件
 */
export const TableDataRenderer = ({
  loading,
  error,
  data,
  children,
  onRetry,
  onCreate,
  emptyType = 'data',
  createText = '添加数据',
  ...props
}) => {
  return (
    <DataRenderer
      loading={loading}
      error={error}
      data={data}
      emptyComponent={
        <ListEmptyState
          type={emptyType}
          onCreate={onCreate}
          onRefresh={onRetry}
          createText={createText}
        />
      }
      errorProps={{ onRetry }}
      {...props}
    >
      {children}
    </DataRenderer>
  );
};

/**
 * 卡片数据渲染组件
 */
export const CardDataRenderer = ({
  loading,
  error,
  data,
  children,
  cardTitle,
  skeletonRows = 4,
  ...props
}) => {
  return (
    <DataRenderer
      loading={loading}
      error={error}
      data={data}
      loadingComponent={<CardLoading title={cardTitle} rows={skeletonRows} />}
      {...props}
    >
      {children}
    </DataRenderer>
  );
};

/**
 * 列表数据渲染组件
 */
export const ListDataRenderer = ({
  loading,
  error,
  data,
  children,
  onRetry,
  onCreate,
  emptyType = 'data',
  emptyDescription,
  ...props
}) => {
  return (
    <DataRenderer
      loading={loading}
      error={error}
      data={data}
      emptyComponent={
        <ListEmptyState
          type={emptyType}
          description={emptyDescription}
          onCreate={onCreate}
          onRefresh={onRetry}
        />
      }
      errorProps={{ onRetry }}
      {...props}
    >
      {children}
    </DataRenderer>
  );
};

/**
 * 统计数据渲染组件
 */
export const StatsDataRenderer = ({
  loading,
  error,
  data,
  children,
  onRetry,
  skeletonCount = 4,
  ...props
}) => {
  const StatsLoading = () => (
    <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>
      {Array.from({ length: skeletonCount }, (_, index) => (
        <CardLoading key={index} rows={1} />
      ))}
    </div>
  );

  return (
    <DataRenderer
      loading={loading}
      error={error}
      data={data}
      loadingComponent={<StatsLoading />}
      errorProps={{ onRetry }}
      emptyType="data"
      emptyProps={{ description: '暂无统计数据' }}
      {...props}
    >
      {children}
    </DataRenderer>
  );
};

/**
 * 搜索结果渲染组件
 */
export const SearchResultRenderer = ({
  loading,
  error,
  data,
  children,
  searchTerm,
  onClearSearch,
  onRetry,
  ...props
}) => {
  return (
    <DataRenderer
      loading={loading}
      error={error}
      data={data}
      emptyComponent={
        <EmptyState
          type="search"
          description={searchTerm ? `没有找到包含 "${searchTerm}" 的结果` : '请输入搜索关键词'}
          actions={onClearSearch ? [
            <button key="clear" onClick={onClearSearch}>清除搜索</button>
          ] : []}
        />
      }
      errorProps={{ onRetry }}
      {...props}
    >
      {children}
    </DataRenderer>
  );
};

export default DataRenderer;